package com.toune.movie.service;

import android.annotation.SuppressLint;
import android.app.Service;
import android.content.Context;
import android.content.Intent;
import android.media.MediaPlayer;
import android.os.Binder;
import android.os.Bundle;
import android.os.Handler;
import android.os.IBinder;
import android.os.Message;

import com.toune.movie.base.myUtil.MyUtil;
import com.toune.movie.vo.MusicVo;
import com.vondear.rxtool.RxFileTool;
import com.yhao.floatwindow.FloatWindow;

public class MusicService extends Service {

    /**
     * 调用此服务使用startService方法，不走onBind，直接走onCreate
     */
    private static MediaPlayer mediaPlayer;
    private static Intent intent;
    private static int playPosition; //当前播放的音乐在播放列表中的位置
    private static MusicVo.DataBean musicVo; //当前播放音乐实例
    private static String localPath = "";//本地音乐文件的存放位置

    public MusicService newInstance() {
        return MusicService.this;
    }

    public MusicService() {
    }

    @Override
    public IBinder onBind(Intent intent) {
        // TODO: Return the communication channel to the service.
        throw new UnsupportedOperationException("Not yet implemented");
    }

    @Override
    public void onCreate() {
        super.onCreate();
    }

    private OnMediaListener onMediaListener;

    public void setOnMediaListener(OnMediaListener onMediaListener) {
        this.onMediaListener = onMediaListener;
    }

    public MediaPlayer getMediaPlayer() {
        return mediaPlayer;
    }

    public void singlePlay(MusicVo.DataBean dataBean, String localPath, int playPosition) {
        this.playPosition = playPosition;
        this.musicVo = dataBean;
        this.localPath = localPath;
        if (mediaPlayer != null) {
            mediaPlayer.stop();
        }
        MyUtil.showMusicFloatWindow(musicVo);
        mediaPlayer = new MediaPlayer();
        mediaPlayer.setOnPreparedListener(new MediaPlayer.OnPreparedListener() {
            @Override
            public void onPrepared(MediaPlayer mp) {
                if (onMediaListener != null) {
                    onMediaListener.onMediaPrepared(mp);
                }
                mediaPlayer.start();
                handler.post(runnable);
            }
        });
        mediaPlayer.setOnCompletionListener(new MediaPlayer.OnCompletionListener() {
            @Override
            public void onCompletion(MediaPlayer mp) {
                if (onMediaListener != null) {
                    onMediaListener.onMediaCompletion(mp);
                }
            }
        });
        mediaPlayer.reset();
        try {
            if (localPath != null && RxFileTool.isFileExists(localPath)) {
                mediaPlayer.setDataSource(localPath);
                mediaPlayer.prepare();
            } else {
                mediaPlayer.setDataSource(musicVo.getUrl());
                mediaPlayer.prepare();
            }
        } catch (Exception e) {
            if (onMediaListener != null) {
                onMediaListener.onError();
            }
            handler.removeCallbacks(runnable);
            e.printStackTrace();
            return;
        }
    }

    public interface OnMediaListener {
        /**
         * 资源准备好了
         *
         * @param mp
         */
        void onMediaPrepared(MediaPlayer mp);

        /**
         * 资源播放完了
         *
         * @param mp
         */
        void onMediaCompletion(MediaPlayer mp);

        /**
         * 资源出问题了
         */
        void onError();
    }

    /**
     * 切换资源
     *
     * @param dataBean
     * @param localPath
     * @param playPosition
     */
    public void resetMusic(MusicVo.DataBean dataBean, String localPath, int playPosition) {
        if (musicVo == null || musicVo.getUrl() != dataBean.getUrl()) {//如果和之前放的那首歌一致则不再重新播放
            this.playPosition = playPosition;
            this.musicVo = dataBean;
            this.localPath = localPath;
            if (mediaPlayer != null) {
                mediaPlayer.stop();
            }
            MyUtil.showMusicFloatWindow(musicVo);
            mediaPlayer = new MediaPlayer();
            mediaPlayer.setOnPreparedListener(new MediaPlayer.OnPreparedListener() {
                @Override
                public void onPrepared(MediaPlayer mp) {
                    if (onMediaListener != null) {
                        onMediaListener.onMediaPrepared(mp);
                    }
                    mediaPlayer.start();
                    handler.post(runnable);
                }
            });
            mediaPlayer.setOnCompletionListener(new MediaPlayer.OnCompletionListener() {
                @Override
                public void onCompletion(MediaPlayer mp) {
                    if (onMediaListener != null) {
                        onMediaListener.onMediaCompletion(mp);
                    }
                }
            });
            mediaPlayer.reset();
            try {
                if (localPath != null && RxFileTool.isFileExists(localPath)) {
                    mediaPlayer.setDataSource(localPath);
                    mediaPlayer.prepare();
                } else {
                    mediaPlayer.setDataSource(musicVo.getUrl());
                    mediaPlayer.prepare();
                }
            } catch (Exception e) {
                if (onMediaListener != null) {
                    onMediaListener.onError();
                }
                handler.removeCallbacks(runnable);
                e.printStackTrace();
                return;
            }
        } else {
            if (onMediaListener != null) {
                onMediaListener.onMediaPrepared(mediaPlayer);
            }
            handler.post(runnable);
        }
    }

    private long time = 100;
    /**
     * 内置定时刷新器
     */
    @SuppressLint("HandlerLeak")
    Handler handler = new Handler();
    Runnable runnable = new Runnable() {
        @Override
        public void run() {
            if (onHandlerListener != null) {
                onHandlerListener.handlerMsg(mediaPlayer);
            }
            handler.post(runnable);
        }
    };

    public Handler initHandler() {
        handler.post(runnable);
        return handler;
    }

    private OnHandlerListener onHandlerListener;

    public void setOnHandlerListener(OnHandlerListener onHandlerListener) {
        this.onHandlerListener = onHandlerListener;
    }

    public interface OnHandlerListener {
        void handlerMsg(MediaPlayer mp);
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        if (mediaPlayer != null) {
            mediaPlayer.stop();
        }
        if (intent != null) {
            intent = null;
        }
        musicVo = null;
        localPath = null;
        playPosition = 0;
        FloatWindow.destroy();
    }

    public static void startThis(Context context) {
        if (intent == null) {
            intent = new Intent(context, MusicService.class);
            context.startService(intent);
        }
    }

    public static void stopThis(Context context) {
        if (intent != null) {
            context.stopService(intent);
        }
    }
}
